import { ref, watch } from 'vue';
import eventBus from 'vue3-eventbus';

export const isConnected = ref(false);
export const WS_URL = 'ws://localhost:8080';

let socket = null;
let timer = null;

export function initWebSocket(url) {
    try {
        socket = new WebSocket(url);
    } catch(err) {
        isConnected.value = false;
    }

    socket.onopen = () => {
        isConnected.value = true;
        eventBus.emit('socket-connected', '以通过本地 WS 网络连接弹幕软件');

        // 发送连接成功消息
        sendMessage({ clientName: 'Leaderboard_CS' });
        clearInterval(timer);
        timer = null;
    };

    socket.onmessage = (event) => {
        try {
            const data = JSON.parse(event.data);
            console.log('WebSocket 消息:', data);
            eventBus.emit('socket-message', data);
        } catch (e) {
            console.log('消息解析失败:', e);
            eventBus.emit('socket-message', event.data);
        }
    };

    socket.onclose = () => {
        if (timer != null) {
            return;
        }

        isConnected.value = false;
        eventBus.emit('socket-disconnected', '未连接弹幕软件');
    };

    socket.onerror = (error) => {
        console.log('WebSocket 错误:', error);
        eventBus.emit('socket-error', error);
    };

    return socket;
}

// 发送消息
export function sendMessage(message) {
    if (!socket || socket.readyState !== WebSocket.OPEN) {
        console.error('WebSocket 未连接，无法发送消息');
        return false;
    }

    // 如果消息是对象，转换为JSON字符串
    if (typeof message === 'object') {
        message = JSON.stringify(message);
    }

    socket.send(message);
    return true;
}

// 关闭连接
export function closeConnection() {
    if (socket) {
        socket.close();
        socket = null;
    }
}

// 重新连接
export function reconnect(url) {
    eventBus.emit('socket-reconnect', '重新连接弹幕软件中');
    return initWebSocket(url);
}

watch(isConnected, newValue => {
    if (newValue == false) {
        timer = setInterval(() => reconnect(WS_URL), 1000)
    } else {
        clearInterval(timer);
        timer = null
    }
}, { immediate: true })

// 导出 WebSocket 实例
export default {
    initWebSocket,
    sendMessage,
    closeConnection,
    reconnect,
    isConnected,
    WS_URL
}; 